<?php

/**
 * Description of Application_Model_Portable
 *
 * @author Jean Brito
 */
abstract class Application_Model_Portable extends Application_Model_Base {

    protected $_server;
    protected $_url = '';
    protected $_dbname;
    protected $_user;
    protected $_password;
    protected $_host;

    protected function _getHost() {
        if ($this->_host)
            return $this->_host;
        $client = new Zend_Http_Client("http://www.agentenet.com.br/ip/" . $this->_server . ".htm");
        $this->_host = 'http://' . str_replace('\';', '', str_replace('ip=\'', '', $client->request()->getBody()));
        return $this->_host;
    }

    protected $_hperm;

    protected function _open() {
        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/Themas/Autenticar.php');
        $client->setParameterPost('EMPRESA', $this->_dbname);
        $client->setParameterPost('LOGIN', $this->_user);
        $client->setParameterPost('PASSWORD', $this->_password);
        $hperm = +str_replace('\';', '', str_replace("<script>location='../Themas/ie-Frame.php?HPERM=", '', $client->request(Zend_Http_Client::POST)->getBody()));
        if (!$hperm) {
            $this->_hperm = '';
            return false;
        }
        $this->_hperm = $hperm;
        return true;
    }

    protected function _close() {
        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/Themas/Autenticar.php');
        $client->setParameterGet('HEPRM', $this->_hperm);
        $client->request();
        return true;
    }

    public function index($filter = '', $start = '', $limit = '', $sort = '') {
        $params = Array(
            'filter' => $filter,
            'start' => $start,
            'limit' => $limit,
            'sort' => $sort,
        );

        $result = Array();
        $this->_open();

        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/FuncoesAuxiliares/portable.php');
        $client->setParameterGet('HPERM', $this->_hperm);
        $client->setParameterPost('Table', $this->_portable);

        if (isset($params['sort'])) {
            $sort = Zend_Json::decode($params['sort']);
            $orderby = "";
            foreach ($sort as $field) {
                if (isset($this->_portableField[$field['property']])) {
                    $orderby.="," . $this->_portableField[$field['property']] . " " . $field['direction'];
                }
                $orderby = substr($orderby, 1, strlen($orderby));
            }
            unset($params['sort']);
            if ($orderby != '')
                $params['sort'] = $orderby;
        }

        foreach ($params as $field => $value)
            $client->setParameterPost($field, $value);

        $result = $client->request(Zend_Http_Client::POST)->getBody();
        try {
            $result = Zend_Json::decode($result);
            if ($result['success']) {
                if (count($this->_portableField)) {
                    $data = Array();
                    foreach ($result['data'] as $precord) {
                        $record = Array();
                        foreach ($this->_portableField as $field => $pfield) {
                            if (isset($precord[$pfield]))
                                $record[$field] = $precord[$pfield];
                        }
                        $data[] = $record;
                    }
                    $result['data'] = $data;
                }
            }
        } catch (Exception $e) {
            echo "Error:" . $result;
            echo $e->getCode();
            exit;
        }
        $this->_close();

        foreach($result['data'] as &$model){
            $this->getActions($model);
        }
        return $result;
    }

    public function post($params) {
        $result = Array();
        $this->_open();

        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/FuncoesAuxiliares/portable.php');
        $client->setParameterGet('HPERM', $this->_hperm);
        $client->setParameterPost('Table', $this->_portable);
        $client->setParameterPost('Method', 'POST');

        $data = array();
        foreach ($this->_portableField as $field => $pfield) {
            if (isset($params[$field]))
                $data[$pfield] = $params[$field];
        }

        foreach ($data as $field => $value)
            $client->setParameterPost($field, $value);

        try {
            $result = $client->request(Zend_Http_Client::POST)->getBody();
            $result = Zend_Json_Decoder::decode($result);
            if ($result['success']) {
                if (count($this->_portableField)) {
                    $data = Array();
                    $precord = $result['data'];
                    $record = Array();
                    foreach ($this->_portableField as $field => $pfield) {
                        if (isset($precord[$pfield]))
                            $record[$field] = $precord[$pfield];
                    }
                    $result['data'] = $record;
                }
            }
        } catch (Zend_Json_Exception $e) {
            echo "Error:" . $result;
            print "<pre>";
            print_r($e);
            print "</pre>";
            exit;
        }
        return $result;
    }

    public function getSqlPrimaryKEY($id) {
        $where = "";
        foreach ($this->getFields() as $field) {
            $fieldclass = 'Application_Model_Fields_' . $field['type'];
            $sqlSetup = $fieldclass::getCreateSql($field);
            if (isset($sqlSetup['sqlPrimaryKEY']))
                if (isset($this->_portableField[$field['name']])) {
                    $where.="(" . $this->_portableField[$field['name']] . "=$id)";
                }
        }
        return $where;
    }

    public function delete($id) {
        $result = Array();
        $this->_open();

        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/FuncoesAuxiliares/portable.php');
        $client->setParameterGet('HPERM', $this->_hperm);
        $client->setParameterPost('Table', $this->_portable);
        $client->setParameterPost('Method', 'DELETE');
        $client->setParameterPost('filter', $this->getSqlPrimaryKEY($id));
        try {
            $result = $client->request(Zend_Http_Client::POST)->getBody();
            $result = Zend_Json_Decoder::decode($result);
        } catch (Zend_Json_Exception $e) {
            echo "Error:" . $result;
            print "<pre>";
            print_r($e);
            print "</pre>";
            exit;
        }
        return $result;
    }

    public function put($id, $params) {
        $result = Array();
        $this->_open();

        $client = new Zend_Http_Client($this->_getHost() . '/' . $this->_url . '/FuncoesAuxiliares/portable.php');
        $client->setParameterGet('HPERM', $this->_hperm);
        $client->setParameterPost('Table', $this->_portable);
        $client->setParameterPost('Method', 'PUT');
        $client->setParameterPost('filter', $this->getSqlPrimaryKEY($id));
        
        $data = array();
        foreach ($this->_portableField as $field => $pfield) {
            if (isset($params[$field]))
                $data[$pfield] = $params[$field];
        }

        foreach ($data as $field => $value)
            $client->setParameterPost($field, $value);
        
        try {
            $result = $client->request(Zend_Http_Client::POST)->getBody();
            $result = Zend_Json_Decoder::decode($result);
            if ($result['success']) {
                if (count($this->_portableField)) {
                    $data = Array();
                    $precord = $result['data'];
                    $record = Array();
                    foreach ($this->_portableField as $field => $pfield) {
                        if (isset($precord[$pfield]))
                            $record[$field] = $precord[$pfield];
                    }
                    $result['data'] = $record;
                }
            }
        } catch (Zend_Json_Exception $e) {
            echo "Error:" . $result;
            print "<pre>";
            print_r($e);
            print "</pre>";
            exit;
        }
        return $result;
    }

}
